/**
 * Copyright 2014 the original author or authors. All rights reserved.
 */
package com.visionet.security.utils;

import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.visionet.security.base.constants.Algorihtm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.visionet.jumper.core.exception.runtime.FrameworkException;

/**
 * 
 *
 * @author suxiaojing
 * @date 
 * @since 0.0.1
 */
public class CipherUtils {
	private final static Logger logger = LoggerFactory.getLogger(CipherUtils.class);

	public static String generateKey(String algorithm) {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
			keyGenerator.init(128);
			SecretKey key = keyGenerator.generateKey();
			return CodecUtils.encodeHexString(key.getEncoded());
		} catch (NoSuchAlgorithmException e) {
			logger.error("No such algorithem [{}] support", algorithm);
			throw new FrameworkException(e.getMessage(),e);
		}
	}

	public static Key transformKey(String key) {
		return new SecretKeySpec(key.getBytes(), Algorihtm.BLOWFISH);
	}
	
	public static Cipher getCipher(String algorithm) {
		try {
			return Cipher.getInstance(algorithm);
		} catch (Exception e) {
			logger.error("No such algorithem [{}] support", algorithm);
			throw new FrameworkException(e.getMessage(),e);
		}
	}

	public static byte[] encrypt(String data, String key, String algorihtm) {
		Key secureKey = transformKey(key);
		Cipher cipher = getCipher(algorihtm);
		try {
			cipher.init(Cipher.ENCRYPT_MODE, secureKey);
			return cipher.doFinal(data.getBytes());
		} catch (Exception e) {
			logger.error("encrypt due to error, data [{}], key [{}], algorihtm [{}]", data, key, algorihtm);
			throw new FrameworkException(e.getMessage(),e);
		}
	}

	public static byte[] decrype(byte[] data, String key, String algorihtm) {
		Key secureKey = transformKey(key);
		Cipher cipher = getCipher(algorihtm);
		try {
			cipher.init(Cipher.DECRYPT_MODE, secureKey);
			return cipher.doFinal(data);
		} catch (Exception e) {
			logger.error("Decrypt due to error, data [{}], key [{}], algorihtm [{}]", data, key, algorihtm);
			throw new FrameworkException(e.getMessage(),e);
		}
	}

	public static String blowfishEncryptHex(String data, String key) {
		return CodecUtils.encodeHexString(encrypt(data, key, Algorihtm.BLOWFISH));
	}

	public static String blowfishDecryptHex(String data, String key) {
		return new String(decrype(CodecUtils.decodeStringHex(data), key, Algorihtm.BLOWFISH));
	}


}
